package com.zwy.ubts.controller;

import com.yg.yws.annotation.YWebPath;
import com.yg.yws.annotation.YWebServlet;
import com.yg.yws.beans.RetType;
import com.zwy.ubts.bean.Address;
import com.zwy.ubts.bean.BookType;
import com.zwy.ubts.bean.User;
import com.zwy.ubts.service.*;
import com.zwy.ubts.service.impl.AddressServiceImpl;
import com.zwy.ubts.service.impl.BookServiceImpl;
import com.zwy.ubts.service.impl.BookTypeServiceImpl;
import com.zwy.ubts.service.impl.UserServiceImpl;
import com.zwy.ubts.utils.DataInfo;
import com.zwy.ubts.utils.DateUtil;
import com.zwy.ubts.utils.ImgUtil;
import com.zwy.ubts.utils.Mail;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.zwy.ubts.bean.Book;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Author Zhou Wenying
 * @Description:
 * @Date Created in 15:31 2023/3/7
 */
@YWebServlet
public class BookController {

    private BookTypeService bookTypeService = new BookTypeServiceImpl();
    private BookService bookService = new BookServiceImpl();


    @YWebPath("/addBook")
    public RetType addBook(){
        List<BookType> bookTypes = bookTypeService.queryBookTypes();
        Map map = new HashMap<>();
        map.put("bookType",bookTypes);
        return RetType.retForward(DataInfo.PAGE_ROOT+"addBook.jsp",map);
    }

    @YWebPath("/doSaveBook")
    public RetType doSaveBook(String bname,String bauthor,String bpublisher,Float bprice,
                              Float boprice,String btname,String bmark,String file,String select_level,
                                HttpSession session) throws IOException, ServletException {
        /*将web传输过来的图片字符串数据解析为图片数据*/
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = null;
        try { // Base64解码
            bytes = decoder.decodeBuffer(file);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
        } catch (Exception e) {
        }
        System.out.println(file);
        System.out.println(bname);

        String img = DateUtil.getCurrentDateToFileName()+".jpg";
        String uploadFilePath = "D:/instal/Jsp_Home/used-book-trading-system/web/static/image/upImg/"+img;
        FileOutputStream stream = new FileOutputStream(new File(uploadFilePath));
        stream.write(bytes);
        stream.close();

        String createTime = DateUtil.getCurrentDate();
        Integer userId = ((User)session.getAttribute(DataInfo.SISSON_USER)).getUserId();
        Book book = new Book(0,bname,bauthor,bpublisher,img,bprice,boprice,btname,bmark,createTime,userId,0,0,select_level);
        System.out.println("book:"+book.toString());
        bookService.addBook(book);

        return RetType.retRedirect("/user");
    }

    @YWebPath("/showBook")
    public RetType showBook(Integer bookId,HttpSession session,Integer noShow){
        Book book = bookService.selectByBookId(bookId);

        //添加热度（拒绝恶意刷热度）多次点击只记录第一次点击
        if (book != null){
            Object attribute = session.getAttribute("bookid:" + bookId);
            if (attribute == null){
                session.setAttribute("bookid:" + bookId,bookId);
                book.setBookHot(book.getBookHot()+1);
                bookService.updateBookById(book);
        }
        }
        Map map = new HashMap();
        map.put("book",book);
        map.put("noShow",noShow);
        return RetType.retForward(DataInfo.PAGE_ROOT+"showBooks.jsp",map);
    }

    @YWebPath("/bookCart")
    public RetType bookCart(Integer[] bookIds){
        Map map = new HashMap();
        float total = 0f;
        List<Book> books = new ArrayList<>();
        List<Integer> noBooksId = new ArrayList<>();
        if (bookIds != null){
            for (Integer id: bookIds) {//失效数据
                Book book = bookService.selectByBookId(id);
                if (book == null){
                    noBooksId.add(id);
                    continue;
                }
                total += book.getBookMoney();
                books.add(book);
            }
        }
        map.put("noBookId",noBooksId);
        map.put("books",books);
        map.put("total",total);
        return RetType.retForward(DataInfo.PAGE_ROOT+"bookCart.jsp",map);
    }

    @YWebPath("/Cart-indent")
    public RetType CartIndent(Integer[] bookIds,Integer change){
        //change:个人中心如果没有默认地址则会传change去设置默认地址
        Map map = new HashMap();
        List<Book> books = new ArrayList<>();
        if (bookIds != null){
            System.out.println("33333+");
            for (Integer id: bookIds) {
                Book book = bookService.selectByBookId(id);
                if (book == null){
                    continue;
                }
                books.add(book);
            }
        }
        map.put("books",books);
        map.put("change",change);
        return RetType.retForward(DataInfo.PAGE_ROOT+"Cart-indent.jsp",map);
    }

    //根据类别显示书籍
    @YWebPath("/booktypes_list")
    public RetType booktypes_list(Integer bookClassify,String like){
        if (like == null){
            like = "";
        }
        Map map = new HashMap();
        map.put("bookClassify",bookClassify);
        map.put("like",like);
        List<Book> books =null;
        if (bookClassify == null || bookClassify.equals("")){
            books = bookService.selectAllBook(like);
        }else {
            books = bookService.queryBookByClassify(bookClassify,like);
            BookType bookType = bookTypeService.queryBookTypeById(bookClassify);

            map.put("bookType",bookType.getBtName());
        }
        map.put("books",books);
        return RetType.retForward(DataInfo.PAGE_ROOT+"booktypes_list.jsp",map);
    }

    @YWebPath("/getImg")
    public RetType getImg(String img, HttpServletResponse resp) throws IOException {
        String uploadFilePath = "D:/instal/Jsp_Home/used-book-trading-system/web/static/image/upImg/"+img;

        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(img, "UTF-8"));
        //ByteArrayInputStream stream = new ByteArrayInputStream(img);
        FileInputStream stream = new FileInputStream(new File(uploadFilePath));
        ServletOutputStream outputStream = resp.getOutputStream();
        //实现浏览器下下载功能
        IOUtils.copy(stream, outputStream);

        return RetType.retEmpty();
    }


}
